package com.hibase.core.excel.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.hibase.core.excel.entity.MdsExcelBizData;
import com.hibase.core.excel.mapper.MdsExcelBizDataMapper;
import com.hibase.core.excel.service.MdsExcelBizDataService;
import com.hibase.core.excel.util.Validate;
import com.hibase.core.excel.vo.bizdata.MdsExcelBizDataSearchVO;
import com.hibase.core.mybatis.service.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Excel业务数据集 Service 服务实现类
 *
 * @author <a href="mailto:xiongliyi@hichain.com">Ian Xiong</a>
 * @since 1.4.35-V2
 */
@Service
public class MdsExcelBizDataServiceImpl extends BaseServiceImpl<MdsExcelBizDataMapper, MdsExcelBizData> implements MdsExcelBizDataService {

    @Override
    public PageInfo queryPage(MdsExcelBizDataSearchVO searchVO) {
        QueryWrapper<MdsExcelBizData> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MdsExcelBizData::getBeDeleted, Boolean.FALSE);

        if (StrUtil.isNotEmpty(searchVO.getKeyWord())) {
            queryWrapper.lambda().like(MdsExcelBizData::getName, searchVO.getKeyWord());
        }
        if (StrUtil.isNotEmpty(searchVO.getCode())) {
            queryWrapper.lambda().like(MdsExcelBizData::getCode, searchVO.getCode());
        }
        if (StrUtil.isNotEmpty(searchVO.getName())) {
            queryWrapper.lambda().like(MdsExcelBizData::getName, searchVO.getName());
        }

        queryWrapper.lambda().orderByDesc(MdsExcelBizData::getBeActive, MdsExcelBizData::getCreateTime);

        return super.page(searchVO, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizData(MdsExcelBizData entity) {
        hasBizCode(entity.getId(), entity.getCode(), Boolean.TRUE);
        return baseMapper.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBizData(MdsExcelBizData entity) {
        hasBizCode(entity.getId(), entity.getCode(), Boolean.FALSE);
        return baseMapper.insert(entity) > 0;
    }

    private void hasBizCode(String id, String code, Boolean isUpdate) {
        QueryWrapper<MdsExcelBizData> queryWrapper =new QueryWrapper<>();
        queryWrapper.lambda().eq(MdsExcelBizData::getCode, code);
        if (isUpdate) {
            queryWrapper.lambda().ne(MdsExcelBizData::getId, id);
        }

        Integer count = baseMapper.selectCount(queryWrapper);

        Validate.isTrue(count == 0, code + "already exists");
    }

}
